package DBLayer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import ExceptionLayer.CustomException;
import ModelLayer.*;

public class DBTreatment implements IFDBTreatment {
	
	private Connection con;
	private int nextId;

	public DBTreatment()
	{
		con = DBConnection.getInstance().getDBcon();
	}

	public ArrayList<Treatment> getTreatmentsByCatId(int catId) 
	{
		return miscWhere("ID = TreatmentID and CategoryID = " + catId, false);
	}
	
	public ArrayList<Treatment> getAllTreatmentsBySearchword(String word)
	{
		return miscWhere("ID = TreatmentID and Title like '%" + word + "%'", false);
	}
	
	private ArrayList<Treatment> miscWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
	    ArrayList<Treatment> list = new ArrayList<Treatment>();	
		
	    String query = buildQuery(wClause);
  
	    try
	    { 
			Statement stmt = con.createStatement();
		 	stmt.setQueryTimeout(5);
		 	results = stmt.executeQuery(query);
	 	
		 	while(results.next()) 
		 	{
		 		Treatment treatment = buildTreatment(results);
		 		list.add(treatment);	
			}
                 
		 	stmt.close(); 			
		}
	 	catch(Exception e){
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
	    
		return list;
	}
	public Treatment getTreatmentById(int id)
	{
		return singleWhere("ID = " + id);
	}
	
	private Treatment singleWhere(String wClause)
	{
		ResultSet results;
		Treatment treatment = null;
		String query = buildQuery(wClause);
		
		try
		{
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			
			if(results.next())
			{
				treatment = buildTreatment(results);
			}
			
			stmt.close();
			
		}
		
		catch(Exception e)
		{
			System.out.println("Query Exception - Select: "+e);
			e.printStackTrace();
		}
		
		return treatment;
	}
	
	private Treatment buildTreatment(ResultSet result)
	{
		Treatment treatment = new Treatment();
		
		try 
		{
			treatment.setId(result.getInt("ID"));
			treatment.setTitle(result.getString("Title"));
			treatment.setType(result.getString("Type"));
			treatment.setDescription((result.getString("Description")));
			treatment.setPrice(result.getDouble("Price"));
			treatment.setTreatmentCategory(new TreatmentCategory(result.getInt("CategoryID")));
			treatment.setEstimatedTime(result.getInt("EstimatedTime"));
		}
		catch(Exception err)
		{	
			
		}
		
		return treatment;
	}
	
	private String buildQuery(String wClause)
	{
		String query = "Select ID, Title, Type, Description, Price, CategoryID, EstimatedTime FROM Product, Treatment";
		
		if(wClause.length() > 0)
			query = query + " WHERE " + wClause;
		
		return query;
	}
	
	public void insertTreatment(Treatment treatment) throws CustomException
	{
		try 
		{
			//call to get the next id number
	        nextId = GetMax.getMaxId("Select max(ID) from Product");
	        nextId = nextId + 1;
	        System.out.println("next id = " +  nextId);

	        treatment.setId(nextId);
	        	        
			String prodQuery = "INSERT INTO Product (ID, Title, Type, Description, Price) VALUES (?, ?, ?, ?, ?)";
			String treatQuery = "INSERT INTO Treatment (TreatmentID, CategoryID, EstimatedTime) VALUES (?, ?, ?)";
			
			PreparedStatement pstmtProd = con.prepareStatement(prodQuery);
			pstmtProd.setInt(1, nextId);
			pstmtProd.setString(2, treatment.getTitle());
			pstmtProd.setString(3, treatment.getType());
			pstmtProd.setString(4, treatment.getDescription());
			pstmtProd.setDouble(5, treatment.getPrice());
			pstmtProd.executeUpdate();
			
			PreparedStatement pstmtTreat = con.prepareStatement(treatQuery);
			pstmtTreat.setInt(1, nextId);
			pstmtTreat.setInt(2, treatment.getTreatmentCategory().getId());
			pstmtTreat.setInt(3, treatment.getEstimatedTime());
			pstmtTreat.executeUpdate();
		} 
		catch (SQLException sqlEx) 
		{
			throw new CustomException("Der skete en database fejl!");
		}
	}
	
	public void updateTreatment(Treatment treatment) throws CustomException
	{
		try 
		{	        
			String query = "UPDATE Product set Title = ?, Type = ?, Description = ?, Price = ?" +
					" WHERE ID = " + treatment.getId() + " UPDATE Treatment set CategoryID = ?, EstimatedTime = ? WHERE TreatmentID = " + treatment.getId();
			
			PreparedStatement pstmt = con.prepareStatement(query);
			pstmt.setString(1, treatment.getTitle());
			pstmt.setString(2, treatment.getType());
			pstmt.setString(3, treatment.getDescription());
			pstmt.setDouble(4, treatment.getPrice());
			pstmt.setInt(5, treatment.getTreatmentCategory().getId());
			pstmt.setInt(6, treatment.getEstimatedTime());
			pstmt.executeUpdate();
		} 
		catch (SQLException sqlEx) 
		{
			throw new CustomException("Der skete en database fejl!");
		}
	}
	
	public void deleteTreatmentById(int id) throws CustomException, SQLException
	{
		try
		{
			String query = "DELETE FROM Treatment WHERE TreatmentID = " + id
					+ " DELETE FROM TreatmentRel WHERE TreatmentID = " + id
					+ " DELETE FROM Product WHERE ID = " + id;
			
			Statement stmt = con.createStatement();
			
			stmt.executeUpdate(query);
		}
		catch (SQLException sqlEx)
		{
			throw new CustomException("Der skete en database fejl!");
		}
		finally
		{
			String query = "DELETE FROM Treatment WHERE TreatmentID = " + id
					+ " DELETE FROM Product WHERE ID = " + id;
			
			Statement stmt = con.createStatement();
			
			stmt.executeUpdate(query);
		}
	}
	
	public int getMax()
	{
		return nextId;
	}
	
}







